package cn.hh.redis.util;

import java.security.MessageDigest;

/**
 * @ClassName: UOPMD5Utils
 * @Description: MD5工具类
 * @author LAIYONGMIN@FFCS.CN
 * @date 2017年9月4日 上午9:57:15
 */
public class UopMD5Utils {

    public static UopMD5Utils uopMD5Utils;
    /**
     * 实例化
     *
     * @return
     */
    public static UopMD5Utils getInstance() {
        if (uopMD5Utils == null) {
            uopMD5Utils = new UopMD5Utils();
        }
        return uopMD5Utils;
    }

    /**
     * MD5 加密
     *
     * @param src
     * @return
     */
    public static String encryptByMd5(String src) {
        if (src == null) {
            return null;
        }
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(src.getBytes());
            return byte2hex(md5.digest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 二进制转十六进制
     *
     * @param b
     * @return
     */
    private static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }

    public static void main(String[] args) {
        String time = "20170911105954";
        String param = "<ServiceNbr>18905910598</ServiceNbr><DataOfferCode>903075551</DataOfferCode>";
        String key = "D388ACCB7B0729A57E8377DACC1226820986E46B0F1CF523039D41206BF24B9A";
        // 加密

    }



    /**
     * MD5 加密
     *
     * @param src
     * @return
     */
    public static String encryptByMd5Utf8(String src) {
        if (src == null) {
            return null;
        }
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(src.getBytes("UTF-8"));
            return byte2hex(md5.digest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * */
    public final static String getMessageDigest(byte[] buffer) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(buffer);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }


}
